package com.bestillet.kyllingogco;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.DisplayMetrics;
import android.util.Xml;

public class Server {
	public static final String HOME = "http://xmlgate.bestilmad.nu/";
	public static final String MIX = "http://xmlgate.bestilmad.nu/XMLgetmix.asp";
	public static final String ADD = "http://xmlgate.bestilmad.nu/XMLputbasket.asp";
	public static final String INFO = "http://xmlgate.bestilmad.nu/XMLgetshopinfo.asp";
	public static final String MENU = "http://xmlgate.bestilmad.nu/XMLgetMenulist.asp";
	public static final String COPY = "http://xmlgate.bestilmad.nu/XMLcopyOrder.asp";
	public static final String CARD = "http://xmlgate.bestilmad.nu/XMLgetstempelkort.asp";
	public static final String CARDS = "http://xmlgate.bestilmad.nu/XMLgetAntalStempelkort.asp";
	public static final String SHOPS = "http://xmlgate.bestilmad.nu/XMLgetshops.asp";
	public static final String ORDER = "http://xmlgate.bestilmad.nu/saveorder.asp";
	public static final String ORDERS = "http://xmlgate.bestilmad.nu/XMLgetOrders.asp";
	public static final String STATUS = "http://xmlgate.bestilmad.nu/getorderstatus.asp";
	public static final String BASKET = "http://xmlgate.bestilmad.nu/XMLgetbasket.asp";
	public static final String GROUPS = "http://xmlgate.bestilmad.nu/XMLgetmixgroup.asp";
	public static final String STAMPS = "http://xmlgate.bestilmad.nu/XMLgetstempler.asp";
	public static final String HEADER = "http://xmlgate.bestilmad.nu/XMLgetmixheader.asp";
	public static final String DELETE = "http://xmlgate.bestilmad.nu/XMLdeletebasketitem.asp";
	public static final String REGISTER = "http://xmlgate.bestilmad.nu/XMLregisterUser.asp";
	public static final String BASKETID = "http://xmlgate.bestilmad.nu/XMLgetBasketId.asp";
	public static final String CAMPAIGN = "http://xmlgate.bestilmad.nu/XMLgetcampaign.asp";
	public static final String CATEGORIES = "http://xmlgate.bestilmad.nu/XMLgetkategorilist.asp";
	public static final String PRODUCT_IMAGES = "http://m.kyllingogco.dk/products/";
	public static final String CAMPAIGN_IMAGES = "http://m.kyllingogco.dk/img/";
	
	public static InputStream get(String urlString) throws IOException {
		InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
                  
        if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
 
            response = httpConn.getResponseCode();                
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");           
        }
        return in; 
    }
	
	public static InputStream post(String urlString, String xml) throws IOException {
		InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
                  
        if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            
    		DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());
    		out.write(xml.getBytes("UTF-8"));
    		out.flush();
    		out.close();
            
            httpConn.connect();
 
            response = httpConn.getResponseCode();                
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");           
        }
        return in;
    }
	
	public static XmlPullParser toXmlParser(InputStream in) throws XmlPullParserException, NullPointerException, IllegalArgumentException {
		XmlPullParser parser = Xml.newPullParser();
		parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
    	parser.setInput(in, "UTF-8");
		return parser;
	}
	
	public static Bitmap downloadBitmap(InputStream in, Activity activity) throws IOException, NullPointerException, OutOfMemoryError {
        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeStream(in);
        
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scaleWidth = metrics.scaledDensity;
        float scaleHeight = metrics.scaledDensity;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        
        in.close();
        return resizedBitmap;
    }
	
	public static String getAuthentication(Context context) {
		ShopApplication app = (ShopApplication) context.getApplicationContext();
		return "<?xml version='1.0' encoding='UTF-8'?><Getshopinfo><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopID>" + app.getShop().getIdx() + "</ShopID></Getshopinfo>";
	}
	
	public static String getAuthenticationShop(Context context) {
		ShopApplication app = (ShopApplication) context.getApplicationContext();
		return "<?xml version='1.0' encoding='UTF-8'?><Getshopinfo><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopID>" + app.getKundeId() + "</ShopID><Android>1</Android><iOS>0</iOS></Getshopinfo>";
	}
	
	public static String getAuthenticationCampaign(Context context) {
		ShopApplication app = (ShopApplication) context.getApplicationContext();
		return "<?xml version='1.0' encoding='UTF-8'?><GetCampaign><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopID>" + app.getShop().getIdx() + "</ShopID></GetCampaign>";
	}
	
	public static String getAuthenticationMenu(Context context, int overskriftId) {
		ShopApplication app = (ShopApplication) context.getApplicationContext();
		return "<?xml version='1.0' encoding='UTF-8'?><GetMenu><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopID>" + app.getShop().getIdx() + "</ShopID><OverskriftID>" + overskriftId + "</OverskriftID></GetMenu>";
	}
	
	public static String getAuthenticationMix(Context context, int mixId) {
		ShopApplication app = (ShopApplication) context.getApplicationContext();
		return "<?xml version='1.0' encoding='UTF-8'?><GetMix><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopID>" + app.getShop().getIdx() + "</ShopID><MixID>" + mixId + "</MixID></GetMix>";
	}
	
	public static String getAuthenticationMixGroups(Context context, int groupId) {
		ShopApplication app = (ShopApplication) context.getApplicationContext();
		return "<?xml version='1.0' encoding='UTF-8'?><GetMixGroups><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopID>" + app.getShop().getIdx() + "</ShopID><GroupID>" + groupId + "</GroupID></GetMixGroups>";
	}
	
	public static String getAuthenticationMixHeaders(Context context, int headerId) {
		ShopApplication app = (ShopApplication) context.getApplicationContext();
		return "<?xml version='1.0' encoding='UTF-8'?><GetMixHeaders><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopID>" + app.getShop().getIdx() + "</ShopID><HeaderID>" + headerId + "</HeaderID></GetMixHeaders>";
	}
	
	public static String getAuthenticationCard(Context context) {
		ShopApplication app = (ShopApplication) context.getApplicationContext();
		return "<?xml version='1.0' encoding='UTF-8'?><GetStempelkort><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><KundeID>" + app.getKundeId() + "</KundeID></GetStempelkort>";
	}
	
	public static String getAuthenticationStamps(String telefon, int idx) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetStempler><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><Idx>" + idx + "</Idx><Telefon>" + telefon + "</Telefon></GetStempler>";
	}
	
	public static String getAuthenticationBasketId(String telefon, int shopId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetBasketId><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId><Telefon>" + telefon + "</Telefon></GetBasketId>";
	}
	
	public static String getAuthenticationNumberOfCards(String telefon, int kundeId) {
		return "<?xml version='1.0' encoding='UTF-8'?><GetStamps><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><KundeId>" + kundeId + "</KundeId><Telefon>" + telefon + "</Telefon></GetStamps>";
	}
	
	public static String getAuthenticationOrders(String telefon, int shopId) {
		return "<?xml version='1.0' encoding='UTF-8'?><Orders><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><ShopId>" + shopId + "</ShopId><Telefon>" + telefon + "</Telefon></Orders>";
	}
	
	public static String getAuthenticationNotification(String regId, String telefon, int shopId, int kundeId) {
		return "<?xml version='1.0' encoding='UTF-8'?><Notification><Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication><Token>" + regId + "</Token><ShopId>" + shopId + "</ShopId><KundeId>" + kundeId + "</KundeId><Telefon>" + telefon + "</Telefon><Platform>Android</Platform></Notification>";
	}
	
	public static String getBasketItemXml(int shopId, int basketId, Item item) {
		String xml = "<?xml version='1.0' encoding='UTF-8'?><Basket>";
		xml += "<Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication>";
		xml += "<ShopId>" + shopId + "</ShopId>";
		xml += "<BasketId>" + basketId + "</BasketId>";
		xml += "<Antal>" + item.getAmount() + "</Antal>";
		xml += "<MenuIdx>" + item.getMenuIdx() + "</MenuIdx>";
		xml += "<OverskriftId>" + item.getCategoryId() + "</OverskriftId>";

		for (MixHeader h : item.getHeaders()) {
			xml += "<Header id=\"" + h.getIdx() + "\">";
			for (Mix m : h.getMix()) {
				if (!m.isHeader()) {
					xml += "<Mix id=\"" + m.getIdx() + "\">";
					switch (m.getType()) {
					case 1:
						xml += "<Option id=\"" + m.getChoice().getIdx() + "\"" + " fyld=\"" + m.getChoice().getFill().replace("&", "&amp;") + "\"" +  " pris=\"" + m.getChoice().getPrice() + "\"></Option>";
						break;
					case 2:
						for (Option o : m.getChoices())
							xml += "<Option id=\"" + o.getIdx() + "\"" + " fyld=\"" + o.getFill().replace("&", "&amp;") + "\"" + " pris=\"" + o.getPrice() + "\"></Option>";
						break;
					}
					xml += "</Mix>";
				}
			}
			xml += "</Header>";
		}
		
		for (MixGroup g : item.getGroups()) {
			xml += "<Group id=\"" + g.getIdx() + "\">";
			for (Mix m : g.getMix()) {
				if (!m.isHeader()) {
					xml += "<Mix id=\"" + m.getIdx() + "\">";
					switch (m.getType()) {
					case 1:
						xml += "<Option id=\"" + m.getChoice().getIdx() + "\"" + " fyld=\"" + m.getChoice().getFill().replace("&", "&amp;") + "\"" +  " pris=\"" + m.getChoice().getPrice() + "\"></Option>";
						break;
					case 2:
						for (Option o : m.getChoices())
							xml += "<Option id=\"" + o.getIdx() + "\"" + " fyld=\"" + o.getFill().replace("&", "&amp;") + "\"" + " pris=\"" + o.getPrice() + "\"></Option>";
						break;
					}
					xml += "</Mix>";
				}
			}
			xml += "</Group>";
		}
		
		for (Mix m : item.getMix()) {
			if (!m.isHeader()) {
				xml += "<Mix id=\"" + m.getIdx() + "\">";
				switch (m.getType()) {
				case 1:
					xml += "<Option id=\"" + m.getChoice().getIdx() + "\"" + " fyld=\"" + m.getChoice().getFill().replace("&", "&amp;") + "\"" +  " pris=\"" + m.getChoice().getPrice() + "\"></Option>";
					break;
				case 2:
					for (Option o : m.getChoices())
						xml += "<Option id=\"" + o.getIdx() + "\"" + " fyld=\"" + o.getFill().replace("&", "&amp;") + "\"" + " pris=\"" + o.getPrice() + "\"></Option>";
					break;
				}
				xml += "</Mix>";
			}
		}

		xml += "</Basket>";
		return xml;
	}
	
	public static String getDeleteBasketItemXml(int idx, int shopId, int basketId) {
		String xml = "<?xml version='1.0' encoding='UTF-8'?><Basket>";
		xml += "<Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication>";
		xml += "<Idx>" + idx + "</Idx>";
		xml += "<ShopId>" + shopId + "</ShopId>";
		xml += "<BasketId>" + basketId + "</BasketId>";
		xml += "</Basket>";
		return xml;
	}
	
	public static String getBasketXml(int shopId, int basketId, String phone) {
		String xml = "<?xml version='1.0' encoding='UTF-8'?><Basket>";
		xml += "<Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication>";
		xml += "<ShopId>" + shopId + "</ShopId>";
		xml += "<BasketId>" + basketId + "</BasketId>";
		xml += "<Phone>" + phone + "</Phone>";
		xml += "</Basket>";
		return xml;
	}
	
	public static String getOrderXml(String name, String phone, String message, String early, String late, int shopId, int basketId, int student) {
		String xml = "<?xml version='1.0' encoding='UTF-8'?><Order>";
		xml += "<Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication>";
		xml += "<ShopId>" + shopId + "</ShopId>";
		xml += "<BasketId>" + basketId + "</BasketId>";
		xml += "<Name>" + name + "</Name>";
		xml += "<Phone>" + phone + "</Phone>";
		xml += "<Message>" + message + "</Message>";
		xml += "<Early>" + early + "</Early>";
		xml += "<Late>" + late + "</Late>";
		xml += "<StudentCard>" + student + "</StudentCard>";
		xml += "</Order>";
		return xml;
	}
	
	public static String getOrderStatusXml(int orderIdx, int shopId, int student, String shopName, String address, String city, String zip) {
		String xml = "<?xml version='1.0' encoding='UTF-8'?><OrderStatus>";
		xml += "<Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication>";
		xml += "<OrderIdx>" + orderIdx + "</OrderIdx>";
		xml += "<ShopId>" + shopId + "</ShopId>";
		xml += "<ShopName>" + shopName.replace("&", "&amp;") + "</ShopName>";
		xml += "<Address>" + address + "</Address>";
		xml += "<City>" + city + "</City>";
		xml += "<PostalCode>" + zip + "</PostalCode>";
		xml += "<Student>" + student + "</Student>";
		xml += "</OrderStatus>";
		return xml;
	}
	
	public static String getCopyOrderXml(int currentBasketId, int basketId, int shopId, boolean slet, String phone, String ids) {
		String xml = "<?xml version='1.0' encoding='UTF-8'?><CopyOrder>";
		xml += "<Athentication>{9B9DF5f-6F59-4E88-99D5-F605FAE3C5B5}</Athentication>";
		xml += "<CurrentBasketId>" + currentBasketId + "</CurrentBasketId>";
		xml += "<BasketId>" + basketId + "</BasketId>";
		xml += "<ShopId>" + shopId + "</ShopId>";
		xml += "<Telefon>" + phone + "</Telefon>";
		xml += "<Slet>" + slet + "</Slet>";
		xml += "<Ids>" + ids + "</Ids>";
		xml += "</CopyOrder>";
		return xml;
	}
}